import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class DingRtcVideoView extends StatefulWidget {

  static final Set<int> _viewIdSets = {};
  static addViewId(int viewId) {
    if (_viewIdSets.contains(viewId)) { return; }
    _viewIdSets.add(viewId);
  }
  static removeViewId(int? viewId) {
    _viewIdSets.remove(viewId);
  }
  static bool containsViewId(int viewId) {
    return _viewIdSets.contains(viewId);
  }

  /// 视图创建后的回调，将会返回一个 `viewId`，这个 `viewId` 用于在 Flutter 中唯一标识一个平台视图
  final ValueChanged<int>? onViewCreated;

  /// 手势识别器，用于处理视图的手势事件
  final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;

  /// [PlatformViewHitTestBehavior] 枚举值，用于指定如何进行点击测试。点击测试是用于确定用户点击或触摸的位置是否在视图内。
  final PlatformViewHitTestBehavior? hitTestBehavior;

  const DingRtcVideoView(
      {super.key, this.gestureRecognizers, this.hitTestBehavior, this.onViewCreated});

  @override
  State<StatefulWidget> createState() => _DingRtcVideoViewState();
}

class _DingRtcVideoViewState extends State<DingRtcVideoView> {

  int? _viewId;

  @override
  Widget build(BuildContext context) {
    PlatformViewHitTestBehavior behavior = widget.hitTestBehavior??PlatformViewHitTestBehavior.opaque;
    if (Platform.isAndroid) {
      return AndroidView(
        hitTestBehavior: behavior,
        viewType: 'DingRtcVideoView',
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
      );
    } else if (Platform.isIOS) {
      return UiKitView(
        hitTestBehavior: behavior,
        viewType: 'DingRtcVideoView',
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
      );
    } else if(defaultTargetPlatform == TargetPlatform.ohos) {
      return OhosView(
        hitTestBehavior: behavior,
        viewType: 'DingRtcVideoView',
        onPlatformViewCreated: _onPlatformViewCreated,
        gestureRecognizers: widget.gestureRecognizers,
      );
    }
    return Text('$defaultTargetPlatform is not yet supported by the plugin');
  }

  void _onPlatformViewCreated(int id) async {
    _viewId = id;
    DingRtcVideoView.addViewId(_viewId!);
    widget.onViewCreated?.call(id);
  }

  @override
  void dispose() {
    super.dispose();
    DingRtcVideoView.removeViewId(_viewId);
  }
}